package com.csnf.demo7.dao.Impl;

import com.csnf.demo7.entity.TbCourse;
import com.csnf.demo7.dao.TbCourseDao;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TbDourseDaoImpl implements TbCourseDao {

    @Override
    public List<TbCourse> getCourseList() throws IOException {
        SqlSession sqlSession = getSqlSession();
        List<TbCourse> courseList = sqlSession.selectList("com.csnf.demo7.dao.TbCourseDao.getCourseList");
        sqlSession.close();
        return courseList;
    }

    @Override
    public List<TbCourse> getCourseListBname(String courseName) throws IOException {
        SqlSession sqlSession = getSqlSession();
        List<TbCourse> courseList = sqlSession.selectList("com.csnf.demo7.dao.TbCourseDao.getCourseListBname",courseName);
        sqlSession.close();
        return courseList;
    }

    @Override
    public void addCourse(TbCourse tbCourse) throws IOException {
        SqlSession sqlSession = getSqlSession();
        sqlSession.insert("com.csnf.demo7.dao.TbCourseDao.addCourse",tbCourse);
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public void deleteCourse(Integer id) throws IOException {
        SqlSession sqlSession = getSqlSession();
        sqlSession.delete("com.csnf.demo7.dao.TbCourseDao.deleteCourse",id);
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public void updateCourse(TbCourse tbCourse) throws IOException {
        SqlSession sqlSession = getSqlSession();
        sqlSession.update("com.csnf.demo7.dao.TbCourseDao.updateCourse",tbCourse);
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public TbCourse getCourseById(Integer id) throws IOException {
        SqlSession sqlSession = getSqlSession();
        TbCourse courseById = sqlSession.selectOne("com.csnf.demo7.dao.TbCourseDao.getCourseById", id);
        sqlSession.close();
        return courseById;
    }


    private static SqlSession getSqlSession() throws IOException {
        String paeh = "mybatis-config.xml";
        InputStream resourcesAsStream = Resources.getResourceAsStream(paeh);
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = builder.build(resourcesAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}
